package com.jxd.dianping.service.impl;

import com.jxd.dianping.common.BusinessException;
import com.jxd.dianping.common.EmBusinessError;
import com.jxd.dianping.dao.UserModelMapper;
import com.jxd.dianping.model.UserModel;
import com.jxd.dianping.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserModelMapper userModelMapper;

    @Override
    public UserModel getUser(Integer id) {
        return userModelMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional //数据库操作同时成功同时失败
    public UserModel register(UserModel registerUser) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        // 1. 用户创建时间和更新时间设置为当前时间
        registerUser.setCreateAt(new Date());
        registerUser.setUpdateAt(new Date());
        // 2. 密码加密
        registerUser.setPassword(encodeByMd5(registerUser.getPassword()));
        try {
            // 3. 插入数据
            userModelMapper.insertSelective(registerUser);
        } catch (DuplicateKeyException ex) {
            // 3.1 主键/唯一索引冲突异常
            throw new BusinessException(EmBusinessError.REGISTER_DUP_FAIL);
        }
        // 4. 返回用户模型
        return getUser(registerUser.getId());
    }

    @Override
    public UserModel login(UserModel loginUser) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        UserModel userModel = userModelMapper.selectByTelphoneAndPassword(loginUser.getTelphone(), encodeByMd5(loginUser.getPassword()));
        if (Objects.isNull(userModel)) {
            throw new BusinessException(EmBusinessError.LOGIN_ERROR);
        }
        log.info("用户{}已登录",userModel.getNickName());
        log.info(userModel.toString());
        return userModel;
    }

    @Override
    public Integer countAllUser() {
        return userModelMapper.countAllUser();
    }

    private String encodeByMd5(String rawPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(messageDigest.digest(rawPassword.getBytes(StandardCharsets.UTF_8)));
    }
}
